/*
 * Copyright © 2011 Breachwalls & Company Inc. and other authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.breachwalls.h2p.platform.web.validator;

import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;

/**
 * バリデータのサポートクラス.
 * @author Ken Todoroki
 * @version $Revision$
 */
public class ValidatorSupport {

    private Validator beanValidator;

    public Validator getBeanValidator() {
        return beanValidator;
    }

    public void setBeanValidator(Validator beanValidator) {
        this.beanValidator = beanValidator;
    }

    public void validate(Object target, Errors errors) {
        getBeanValidator().validate(target, errors);
    }

    public void validate(MessageContext messages, Object target) {
        final Errors errors = new BindException(target, target.getClass().getName());
        validate(target, errors);
        saveErrors(messages, errors);
    }

    protected void saveErrors(MessageContext messages, Errors errors) {
        if (errors.hasErrors()) {
            for (ObjectError error : errors.getAllErrors()) {
                saveError(messages, error.getObjectName(), error.getCode(), error.getArguments());
            }
        }
    }

    protected void saveError(MessageContext messages, String source, String code) {
        saveError(messages, source, code, new Object[] {});
    }

    protected void saveError(MessageContext messages, String source, String code, Object[] args) {
        final MessageBuilder builder = new MessageBuilder();
        builder.error().source(source).code(code).args(args);
        messages.addMessage(builder.build());
    }

}
